<template>
  <div>
    <!-- 搜索 -->
    <div class="search">
      <p>商品搜索：</p>
      <div class="searchbox">
        <el-input v-model="input" placeholder="请输入"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="searchType"
          >搜索</el-button
        >
      </div>
    </div>
    <!-- 按钮 -->
    <!-- 新建按钮 -->
    <el-button
      type="primary"
      icon="el-icon-circle-plus-outline"
      class="add"
      @click="addGoods"
      >新建</el-button
    >
    <!-- 导入数据按钮 -->
    <el-button type="primary" class="addData">导入数据</el-button>
    <!-- 表格数据 -->
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column type="index" label="序号" width="120"> </el-table-column>
      <el-table-column prop="skuName" label="商品名称" width="180">
      </el-table-column>
      <el-table-column prop="skuImage" label="商品图片" width="120">
        <template #default="scope">
          <div class="imgBox">
            <img :src="scope.row.skuImage" alt="" />
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="brandName" label="品牌"> </el-table-column>
      <el-table-column prop="unit" label="规格"> </el-table-column>
      <el-table-column prop="price" label="商品价格"> </el-table-column>
      <el-table-column prop="skuClass.className" label="商品类型">
      </el-table-column>
      <el-table-column prop="createTime" label="创建日期"> </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="text" class="left" @click="edit(scope.row)"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 底部按钮 -->
    <div class="footer">
      <div class="left">
        共{{ msg.totalCount }}条记录 第{{ msg.pageIndex }}/{{ msg.totalPage }}页
      </div>
      <div class="button">
        <el-button
          :disabled="pageIndex === 1"
          class="prev"
          @click="changeNum(-1)"
          >上一页</el-button
        ><el-button
          type="primary"
          class="next"
          @click="changeNum(1)"
          :disabled="pageIndex >= msg.totalPage"
          >下一页</el-button
        >
      </div>
    </div>
    <!-- 弹出框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="50%"
      @close="handleClose"
    >
      <!-- <span>这是一段信息</span> -->
      <el-form :model="form" :rules="rules" label-width="120px" ref="form">
        <!-- 商品名称 -->
        <el-form-item label="商品名称" prop="skuName">
          <el-input
            type="text"
            placeholder="请输入"
            v-model="form.skuName"
            maxlength="15"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <!-- 品牌 -->
        <el-form-item label="品牌" prop="brandName">
          <el-input
            type="text"
            placeholder="请输入"
            v-model="form.brandName"
            maxlength="10"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <!-- 商品价格 -->
        <el-form-item label="商品价格(元)" prop="price">
          <el-input-number
            v-model="form.price"
            controls-position="right"
            :min="1"
            :max="10"
            :step="+0.5"
          ></el-input-number>
        </el-form-item>
        <!-- 商品类型 -->
        <el-form-item label="商品类型" prop="value">
          <el-select v-model="form.value" placeholder="请选择">
            <el-option
              v-for="item in searchList"
              :key="item.classId"
              :label="item.className"
              :value="item.classId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 规格 -->
        <el-form-item label="规格" prop="unit">
          <el-input
            type="text"
            placeholder="请输入"
            v-model="form.unit"
            maxlength="10"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <!-- 商品图片 -->
        <el-form-item label="商品图片：">
          <el-upload
            class="avatar-uploader"
            action="http://likede2-admin.itheima.net/likede/api/vm-service/sku/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            name="fileName"
            ref="uploadRef"
          >
            <img v-if="form.skuImage" :src="form.skuImage" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过100kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAll">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getGoods, getGoodsType1, addAll, editGoods } from '@/api/goods'
export default {
  name: 'goodsManage',
  components: {},
  props: {},
  data() {
    return {
      input: '',
      tableData: [],
      dialogVisible: false,
      title: '',
      num: '',
      // 图片上传
      imageUrl: '',
      // msg接收所有的数据
      msg: {},
      searchList: [],
      pageIndex: 1,
      skuId: '',
      form: {
        skuName: '',
        skuImage: '',
        price: '',
        classId: '',
        unit: '',
        brandName: '',
        className: '',
        skuClass: '',
        value: '',
        image: ''
      },
      className: [],
      rules: {
        skuName: [{ required: true, message: '请输入', trigger: 'blur' }],
        brandName: [{ required: true, message: '请输入', trigger: 'blur' }],
        price: [{ required: true, message: '请输入', trigger: 'blur' }],
        className: [{ required: true, message: '请输入', trigger: 'blur' }],
        unit: [{ required: true, message: '请输入', trigger: 'blur' }],
        value: [{ required: true, message: '请选择', trigger: 'blur' }]
      }
    }
  },
  computed: {},
  watch: {},
  async created() {
    this.initData()
    const res = await getGoodsType1()
    console.log(res)
    // 数据结构保持一致
    this.searchList = res.currentPageRecords
  },
  methods: {
    async initData() {
      const obj = {
        pageIndex: this.pageIndex,
        pageSize: this.pageSize
      }
      const res = await getGoods(obj)
      console.log(res)
      // this.tableData = res.currentPageRecords
      this.msg = res
      this.tableData = res.currentPageRecords
      // replace 去除T
      this.tableData.forEach((item) => {
        item.createTime = item.createTime.replace('T', ' ')
      })
      console.log(this.tableData)
      console.log(res.currentPageRecords)
    },
    // 新增商品
    async addGoods() {
      this.dialogVisible = true
      this.title = '新增商品'
    },
    // 搜索商品
    async searchType() {
      const obj = {
        pageIndex: this.form.pageIndex,
        pageSize: this.form.pageSize,
        skuName: this.input
      }
      const res = await getGoods(obj)
      console.log(res)
      this.tableData = res.currentPageRecords
      // replace 去除T
      this.tableData.forEach((item) => {
        item.createTime = item.createTime.replace('T', ' ')
      })
      // console.log(res.currentPageRecords)
    },
    // 上下页
    changeNum(num) {
      this.pageIndex += num
      this.initData()
    },
    // 修改
    edit(row) {
      console.log(row)
      this.skuId = row.skuId
      this.form.classId = row.classId
      this.title = '修改商品'
      this.dialogVisible = true
      this.form = { ...row }
    },
    // 图片上传 组件 action 设置为后台图片上传接口 图片上传成功后 服务器会返回图片链接 使用属性 on-success（上传成功钩子函数） 接收
    handleAvatarSuccess(res, file) {
      this.form.skuImage = res
      // this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png'

      const isLt2M = 100 - file.size / 1024 >= 0

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 100kb!')
      }
      return isJPG && isLt2M
    },
    // 上传商品
    async addAll(id) {
      if (this.title === '新增商品') {
        const obj = {
          brandName: this.form.brandName,
          classId: this.form.value,
          price: this.form.price,
          skuImage: this.form.skuImage,
          skuName: this.form.skuName,
          unit: this.form.unit
        }
        console.log(this.form)
        const res = await addAll(obj)
        console.log(res)
        this.$message.success('添加成功')
      } else {
        console.log(this.skuId)
        const obj = {
          brandName: this.form.brandName,
          classId: this.form.classId,
          price: this.form.price,
          skuImage: this.form.skuImage,
          skuName: this.form.skuName,
          unit: this.form.unit
        }
        console.log(obj)
        await editGoods(obj, this.skuId)
      }
      this.initData()
      this.dialogVisible = false
    },
    handleClose() {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style scoped lang="scss">
.search {
  display: flex;
  align-items: center;
  .el-input {
    width: 200px;
    margin: 20px;
    color: #6188fc;
  }
  .el-button {
    color: #fff;
    background-color: #6188fc;
    border: 0;
  }
}
.footer {
  display: flex;
  align-items: center;
  .left {
    color: #dbdfe5;
    font-weight: 400;
    margin-top: 40px;
    margin-right: 800px;
  }
  .button {
    margin-top: 40px;
    .prev {
      background-color: #edf0f9;
    }
    .next {
      background-color: #d6def7;
      color: #606266;
      border: 0;
    }
  }
}
.add {
  background-color: #fc6733;
  color: #fff;
  border: 0;
  margin-top: 50px;
  margin-bottom: 20px;
  &:hover {
    background-color: #fc6733;
  }
}
.addData {
  background-color: #fbf4f0;
  color: #665c58;
  border: 0;
}
.left {
  color: #7093fc;
  font-size: 16px;
  font-weight: 700;
}
.imgBox {
  width: 30px;
  height: 30px;
  img {
    width: 100%;
    height: 100%;
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
//图片上传
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 86px;
  height: 86px;
  line-height: 86px;
  text-align: center;
}
::v-deep .avatar {
  width: 86px;
  height: 86px;
  display: block;
}
</style>
